package com.itheima.service.impl;

import com.itheima.anno.Log;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpService empService;

    @Override
    public List<Dept> listDept() {
        //调用mapper层获取所有的部门数据
        List<Dept> allDepts = deptMapper.selectAll();

        return allDepts;
    }

    //编译时异常如何回滚？
    // 方案一：将异常抛出，并在Transactional中指定回滚异常 rollbackFor = Exception.class
    // 方案二：直接将编译时异常捕获，并转换为运行时异常抛出
    //事务管理注解
    @Transactional/*(rollbackFor = Exception.class)*/
    @Override
    @Log
    public void deleteDept(Integer id) /*throws FileNotFoundException*/ {
        //1 删除部门
        deptMapper.deleteById(id);


        //2 先删除该部门对应的员工
        //empMapper.deleteByDeptId(id);

        empService.deleteByDeptId(id);


        //System.out.println(1/0);//运行时异常

       /* try {
            new FileInputStream("xxx/xxx/xx.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);//将e编译时异常转换为运行时异常
        }*/


    }

    @Log
    @Override
    public void saveDept(Dept dept) {
        //将创建时间和更新时间初始化
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //调用mapper完成数据插入
        deptMapper.insert(dept);
    }
}
